package com.service;

import com.alipay.api.domain.Car;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.controller.CartController;
import com.entity.Commodity;
import com.entity.TbOrder;
import com.entity.TbOrderItem;
import com.entity.TbOrderItemExample;
import com.mapper.*;
import com.vo.CartVO;
import com.vo.GoodsVO;
import com.vo.TbOrderResDTO;
import jnr.ffi.annotations.In;
import org.bouncycastle.crypto.paddings.TBCPadding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论回复 服务类
 * </p>
 *
 * @author hlt
 * @since 2019-12-21
 */
@Service
@Transactional
public class OrderService {
    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    //获取商品信息；
    public Map<Commodity, String> getGoodsMap(List<GoodsVO> goods) {
        Map<Commodity, String> map = new HashMap<>();
        //根据id获取商品信息
        for (GoodsVO good : goods) {
            String pid = good.getPid();
            //查询商品详情
            //把商品和对应的数量添加daoMap
            if(StringUtils.isEmpty(pid)){
                //CartVO o = (CartVO) redisTemplate.boundHashOps(CartController.CART_KEY).get(good.getCid());
                map.put(commodityMapper.LookCommodity(new Commodity().setCommid(cartService.selectByPrimaryKey(good.getCid()).getPId())),good.getNum()) ;
            }else {
                map.put(commodityMapper.LookCommodity(new Commodity().setCommid(pid.toString())),good.getNum());
            }
        }
        return map;
    }


    /**
     * 创建订单
     *
     * @param order 订单对象
     * @param b     是否立即支付 true 是
     * @return
     */
    public String addOrder(TbOrder order, boolean b) {
        //如果是立即支付的话，就不用关心redis缓存了
        //生成一个id
        order.setId(String.valueOf(idWorker.getId()));
        //订单数量
        int totalNum = 0;
        //订单总金额
        BigDecimal totalMoney = BigDecimal.valueOf(0);

        List<CartVO> orderItem = new ArrayList<>();


        //单间商品
        if (b) {
            //查询库存，场景库存大部分都为1，写死库存
            int kucun = 1;
            if(order.getTotalNum() > kucun || commodityMapper.LookCommodity(new Commodity().setCommid(order.getCommodityid())).getCommstatus() == 4) throw new RuntimeException("库存不足");
            totalNum = order.getTotalNum();
            totalMoney = order.getTotalMoney();
            //查出商品价格
            Commodity commodity = commodityMapper.LookCommodity(new Commodity().setCommid(order.getCommodityid()));

            Integer num = order.getTotalNum();
            BigDecimal count = commodity.getThinkmoney().multiply(new BigDecimal(num));
            orderItem.add(new CartVO(null, commodity.getCommname(), commodity.getThinkmoney(), count, num, order.getCommodityid()));
            cartService.deleteByCommodityid(order.getCommodityid());
        } else {
            for (String commodityid : order.getCommodityids()) {
                //检查库存
                CartVO cartVO = (CartVO) redisTemplate.boundHashOps(CartController.CART_KEY).get(commodityid);
                Commodity commodity = new Commodity().setCommid(commodityid);
                if(cartVO.getCNum() > 1 || commodityMapper.LookCommodity(commodity).getCommstatus() == 4) throw new RuntimeException("商品库存不足或已售出");
                //购物车id
                orderItem.add(cartVO);
                redisTemplate.boundHashOps(CartController.CART_KEY).delete(commodityid);
                //缓存中删除后还要数据库中删除；
                //cartService.deleteByCommodityid(commodityid);
            }
            List<String> commodityids = order.getCommodityids();
            Set<String> collect = new HashSet<>(commodityids);
            //调用批量删除同步数据到购物车
            cartService.deleteByCommodityids(collect);

            for (CartVO item : orderItem) {
                // 价格校验
                BigDecimal price = commodityMapper.LookCommodity(new Commodity().setCommid(item.getCommid())).getThinkmoney();
                if (Objects.equals(price, item.getPrice())) {
                    // 总金额
                    totalMoney = item.getPrice().add(totalMoney);
                } else totalMoney = price.add(totalMoney);

                // 总数量
                totalNum += item.getCNum();
            }
            //从购物车结算的话就清楚缓存
            //redisTemplate.delete(CartController.CART_KEY);
        }
        // 订单商品总数目 = 每个商品数量之和
        order.setTotalNum(totalNum);

        // 订单总金额 = 每个商品金额之和
        order.setTotalMoney(totalMoney);

        // 订单实付金额 = 每个商品实付金额之和
        order.setPayMoney(totalMoney);

        // 订单优惠金额 = 总金额 - 实付金额，暂时为 0
        order.setPreMoney(BigDecimal.valueOf(0));

        // 订单评价状态，0 表示未评价,1 表示已评价
        order.setBuyerRate("0");

        // 订单状态，0 表示未完成，1 表示已完成，2 表示已退货
        order.setOrderStatus("0");

        // 订单支付状态，0 表示未支付，1 表示已支付，2 表示支付失败
        order.setPayStatus("0");

        // 订单删除状态，0 表示未删除
        order.setIsDelete("0");

        // 订单发货状态，0 表示未发货，1 表示已发货，2 表示已收货
        order.setConsignStatus("0");

        /** 暂定
         * 递减库存
         */


        // 先添加订单信息
        tbOrderMapper.insertSelective(order);

        //表示商品在购物车中；
        // 再添加订单明细信息,从购物车中查出
        for (CartVO item : orderItem) {
            TbOrderItem tbOrderItem = new TbOrderItem();
            tbOrderItem.setOrderId(order.getId());
            tbOrderItem.setName(item.getCname());
            tbOrderItem.setNum(item.getCNum());
            tbOrderItem.setPrice(item.getPrice());
            tbOrderItem.setPayMoney(item.getCCount());
            tbOrderItem.setId(item.getCommid());
            Commodity commodity = commodityMapper.LookCommodity(new Commodity(item.getCommid()));
            tbOrderItem.setImage(commodity.getImage());
            tbOrderItem.setPostFee(new BigDecimal(0.00));
            // 是否退货,0 表示未退货，1 表示已退货
            tbOrderItem.setIsReturn("0");
            // 退货状态，0 表示未退货
            tbOrderItem.setIsReturn("0");
            tbOrderItemMapper.insertSelective(tbOrderItem);
            //修改商品状态,已售出
            commodityMapper.ChangeCommstatus(item.getCommid(), 4);
        }
        return order.getId();
    }


    /**
     * 查询订单对象
     * @param order_id
     * @return
     */
    public TbOrder queryOrderById(String order_id) {
        return tbOrderMapper.selectByPrimaryKey(order_id);
    }

    /**
     * 查询支付状态
     * @param order_id
     * @return
     */
    public int queryPayStatus(String order_id) {
        TbOrder order= tbOrderMapper.selectByPrimaryKey(order_id);

        if (Objects.equals(order.getPayStatus(), "1")) {
            //已支付
            return 1;
        } else if (Objects.equals(order.getPayStatus(), "0")) {
            //未支付
            return 0;
        }
        //支付失败
        return 2;
    }

    public int updateOrderStatus(TbOrder order) {
        return tbOrderMapper.updateByPrimaryKeySelective(order);

    }

    public List<TbOrderResDTO> queryAllOrders(int page, int limit, String couserid, String cartKey) {

        List<TbOrderResDTO> tbOrderResDTOS = tbOrderMapper.selectByUserName(page,limit,couserid);
        return tbOrderResDTOS;
    }

    /**
     * 查询所有订单明细
     * @param id
     * @return
     */
    public List<TbOrderItem> getOrderDetail(String id) {
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(Long.valueOf(id));
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(example);
        return tbOrderItems;
    }

    public int deleteOrder(String id) {
        TbOrderItemExample example = new TbOrderItemExample();
        example.createCriteria().andOrderIdEqualTo(Long.valueOf(id));
        int i = tbOrderItemMapper.deleteByExample(example);
        int i1 = tbOrderMapper.deleteByPrimaryKey(id);
        if (i == i1 && i ==1){
            return 1;
        }
        return 0;
    }
}
